package com.yuanzhi.train.str;

import java.util.Objects;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 *  
 *
 * 示例 1：
 *
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * 示例 2：
 *
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *  
 *
 * 提示：
 *
 * 1 <= strs.length <= 200
 * 0 <= strs[i].length <= 200
 * strs[i] 仅由小写英文字母组成
 *
 * @author yuanZhi
 * @since 2022/1/14 14:30
 */
public class LongestCommonPre {
    public static void main(String[] args) {
        String[] strs = {"flower","flow","flight"};
        System.out.println(longestCommonPre(strs));

        String[] strs1 = {"cir","car"};
        System.out.println(longestCommonPre(strs1));
    }
    private static String longestCommonPre(String[] strs){
        if (strs.length == 0){
            return "";
        }
        // 找出最短串
        String shortestStr = strs[0];
        for (int i = 1; i < strs.length; i++) {
            if (strs[i].length() < shortestStr.length()){
                shortestStr = strs[i];
            }
        }

        String longestCommonPre = shortestStr;
        // 双重遍历
        for (String strItem : strs) {
            // 每一个串
            StringBuilder longestCommonPreTemp = new StringBuilder();
            for (int j = 0; j < shortestStr.length(); j++) {
                if (Objects.equals(shortestStr.charAt(j), strItem.charAt(j))) {
                    longestCommonPreTemp.append(shortestStr.charAt(j));
                } else {
                    break;
                }
            }

            if (longestCommonPre.length() > longestCommonPreTemp.length()) {
                longestCommonPre = new String(longestCommonPreTemp);
            }
        }

        return longestCommonPre;
    }
}
